package com.lc.reader.ui.viewmodel

import android.net.Uri
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.lc.reader.data.model.Book
import com.lc.reader.data.repository.BookRepository
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import java.io.File

class BookshelfViewModel(
    private val bookRepository: BookRepository
) : ViewModel() {
    
    val books = bookRepository.getAllBooks()
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5000),
            initialValue = emptyList()
        )
    
    fun importBook(uri: Uri) {
        viewModelScope.launch {
            try {
                // 创建新的Book对象
                val book = Book(
                    title = "示例书籍",
                    author = "示例作者",
                    filePath = uri.toString(),
                    fileSize = 1024 * 1024,
                    format = "EPUB"
                )
                bookRepository.insertBook(book)
            } catch (e: Exception) {
                throw e
            }
        }
    }
    
    fun toggleFavorite(book: Book) {
        viewModelScope.launch {
            val updatedBook = book.copy(isFavorite = !book.isFavorite)
            bookRepository.updateBook(updatedBook)
        }
    }
    
    fun deleteBook(book: Book) {
        viewModelScope.launch {
            bookRepository.deleteBook(book)
        }
    }
}

// 简单的ViewModelFactory
class BookshelfViewModelFactory(
    private val bookRepository: BookRepository
) : ViewModelProvider.Factory {
    
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(BookshelfViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return BookshelfViewModel(bookRepository) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}
